package com.jackson.payparams.utils;

/*
 * Author: JacksonCoder
 * FileName: GerAssessToken
 * Version: 1.0.0
 * Date: 2025/7/14
 */

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

public class GenerateAssessToken {
    public static void main(String[] args) {
        try {
            String clientKey = "CKSandbox-98daa36a-35c8-4481-9e67-25fbd4c3e10a"; // 写死
            // 自定义格式（与你的示例完全一致）
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
            // 获取当前 UTC 时间并格式化
//            String requestTimestamp = ZonedDateTime.now(java.time.ZoneOffset.UTC)
//                    .format(formatter);
            String requestTimestamp = "2025-01-17T06:36:36+00:00"; // 动态生成
            String stringToSign = clientKey + "|" + requestTimestamp;

            String privateKeyPEM = "-----BEGIN PRIVATE KEY-----\n" +
                    "YOU PRIVATE KEY PEM" +
                    "-----END PRIVATE KEY-----";

            privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .replaceAll("\\s", "");
//            System.out.println("this is privateKeyPEM: " + privateKeyPEM);
            byte[] keyBytes = Base64.getDecoder().decode(privateKeyPEM);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(privateKey);
            signature.update(stringToSign.getBytes("UTF-8"));
            byte[] signedBytes = signature.sign();
            String base64Signature = Base64.getEncoder().encodeToString(signedBytes);

            System.out.println("Base64 Signature: " + base64Signature);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
